package com.imooc.miaosha.controller.FeController;

import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.imooc.miaosha.common.Const;
import com.imooc.miaosha.dto.BuyDTO;
import com.imooc.miaosha.dto.GoodsVO;
import com.imooc.miaosha.dto.OrderDTO;
import com.imooc.miaosha.dto.UserDTO;

import com.imooc.miaosha.pojo.User;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.service.SecondKillService;
import com.imooc.miaosha.service.ShippingService;
import com.imooc.miaosha.util.*;

import com.imooc.miaosha.vo.OrderShippingVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@Slf4j
@RequestMapping("secondKill")
public class MiaoShaController {

    @Autowired
    OrderService orderService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    SecondKillService secondKillService;
    @Autowired
    ShippingService shippingService;

    @RequestMapping("afterPropertiesSet")
    @ResponseBody
    public JsonData afterPropertiesSet() {
        List<GoodsVO> GoodsVOList = goodsService.list();
        for (GoodsVO GoodsVO : GoodsVOList) {
            JedisUtil.set(Const.MIAOSHA_STOCK, GoodsVO.getMiaoshaId().toString(), GoodsVO.getMisoshaStock().toString());
        }
        return JsonData.success();

    }


    @RequestMapping("/{path}/buy")
    @ResponseBody
    public JsonData buy(HttpServletRequest request, @PathVariable("path") String path, Long secondKillId, Long shippingId) {
        String loginToken = CookieUtil.readCookie(request);
        UserDTO userDTO = this._getUser(loginToken);
        if (userDTO == null) {
            return JsonData.fail("您还没登录～");
        }
        if (StringUtils.isBlank(path) || StringUtils.isBlank(loginToken) || secondKillId == null) {
            return JsonData.fail("请求非法");
        }
        Map<String, Object> resMap = secondKillService.buy(userDTO.getId(), secondKillId, shippingId, path);
        return JsonData.success(resMap.get("msg").toString(), null);
    }

    @RequestMapping("/buy_mini")
    @ResponseBody
    public JsonData buy(@RequestBody Map<String, Object> paramMap) {
        System.out.println(paramMap.toString());
        String loginToken = (String) paramMap.get("loginToken");
        Integer secondKillId = (Integer) paramMap.get("secondKillId");
        String pathToken = (String) paramMap.get("pathToken");
        String shippingId = (String) paramMap.get("shippingId");
        UserDTO userDTO = this._getUser(loginToken);
        if (userDTO == null) {
            return JsonData.fail("您还没登录～");
        }
        if (StringUtils.isBlank(loginToken) || StringUtils.isBlank(pathToken) || secondKillId == null) {
            return JsonData.fail("请求非法");
        }
        Map<String, Object> resMap = secondKillService.buy(userDTO.getId(), secondKillId.longValue(), Long.valueOf(shippingId), pathToken);
        return JsonData.success(resMap.get("msg").toString(), "抢购成功");
    }

    @RequestMapping("result")
    @ResponseBody
    public JsonData getOrderResult(Long miaoshaId, HttpServletRequest request) {
        String loginToken = CookieUtil.readCookie(request);
        String userJson = JedisUtil.get(Const.LOGIN_TOKEN_PREFIX, loginToken);
        UserDTO userDTO = JsonUtil.String2Obj(userJson, new TypeReference<UserDTO>() {
        });
        OrderShippingVO orderShippingVO = orderService.getOrder(miaoshaId, userDTO.getId());
        if (orderShippingVO != null) {
            return JsonData.success(orderShippingVO.getOrderId());
        } else {
            Long stock = Long.valueOf(JedisUtil.get(Const.MIAOSHA_STOCK, miaoshaId.toString()));
            if (stock > 0) {
                return JsonData.fail("0");
            } else {
                return JsonData.fail("-1");
            }
        }
    }

    /**
     * @param request
     * @param miaoshaId
     * @return
     */
    @RequestMapping("/createpath")
    @ResponseBody
    public JsonData checkOrderToken(HttpServletRequest request, Long miaoshaId, String veryfyCode) {
        String loginToken = CookieUtil.readCookie(request);
        UserDTO userDTO = this._getUser(loginToken);
        if (userDTO == null) {
            return JsonData.fail("用户未登录，请重新登陆");
        }
        Long count = this._increaseClickCount(miaoshaId, userDTO);
        if (count > 10) {
            return JsonData.fail("秒杀请求过于频繁,建议先喝杯咖啡冷静冷静~");
        }
        if (JedisUtil.get(Const.MIAOSHA_CHECK_TOKEN, userDTO.getId() + ":" + miaoshaId) == null) {
            log.error("秒杀id" + miaoshaId);
            String miaoShaToken = Md5Util.passwordToDB(UUID.randomUUID().toString(), "123456");
            JedisUtil.setEx(Const.MIAOSHA_CHECK_TOKEN, userDTO.getId() + ":" + miaoshaId, miaoShaToken, 60);
            return JsonData.success(null, miaoShaToken);
        }
        return JsonData.fail("该账号已在抢购排队中，请勿重复抢购！");
    }

    @RequestMapping("/createpath_mini")
    @ResponseBody
    public JsonData checkOrderToken(@RequestBody Map<String, Object> paramMap) {
        String token = (String) paramMap.get("token");
        Integer secondKillId = (Integer) paramMap.get("secondKillId");
        String shippingId = (String) paramMap.get("shippingId");
        UserDTO userDTO = this._getUser(token);
        if (userDTO == null) {
            return JsonData.fail("用户登录令牌已失效,请重新登录");
        }
        if (shippingId == null || secondKillId == null) {
            return JsonData.fail("输入参数不正确");
        }
        if (!shippingService.isUserShpping(Long.valueOf(shippingId), userDTO.getId())) {
            return JsonData.fail("请不要做非法操作");
        }
        Long count = this._increaseClickCount(secondKillId.longValue(), userDTO);
        if (count > Const.MAX_SECOND_KILL_CLICK_COUNT) {
            return JsonData.fail("秒杀请求过于频繁,建议先喝杯咖啡冷静冷静~");
        }
        if (JedisUtil.get(Const.MIAOSHA_CHECK_TOKEN, userDTO.getId() + ":" + secondKillId) != null) {
            return JsonData.fail("该账号已在抢购排队中，请勿重复抢购！");
        }

        String pathToken = this._retDightPathToken();
        JedisUtil.setEx(Const.MIAOSHA_CHECK_TOKEN, userDTO.getId() + ":" + secondKillId, pathToken, 60);
        return JsonData.success(null, pathToken);


    }

    public Long _increaseClickCount(Long miaoshaId, UserDTO user) {
        String miaoshaCount = JedisUtil.get(Const.MIAOSHA_CLICK_COUNT_PREFIX, miaoshaId + ":" + user.getId());
        if (miaoshaCount == null) {
            JedisUtil.setEx(Const.MIAOSHA_CLICK_COUNT_PREFIX, miaoshaId + ":" + user.getId(), "0", 60);
        }
        return JedisUtil.incr(Const.MIAOSHA_CLICK_COUNT_PREFIX, miaoshaId + ":" + user.getId());
    }

    public UserDTO _getUser(String token) {
        String userJson = JedisUtil.get(Const.LOGIN_TOKEN_PREFIX, token);
        return JsonUtil.String2Obj(userJson, new TypeReference<UserDTO>() {
        });
    }

    public String _retDightPathToken() {
        return Md5Util.passwordToDB(UUID.randomUUID().toString(), "123456");
    }
}
